package com.ztn.iot.zhonghaichi2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ztn.iot.zhonghaichi2.entity.SiteEntity;
import com.ztn.iot.zhonghaichi2.mapper.SiteMapper;
import com.ztn.iot.zhonghaichi2.service.ISiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class SiteServiceImpl implements ISiteService {

    @Autowired
    private SiteMapper siteMapper;

    @Override
    public List<SiteEntity> list() {
        LambdaQueryWrapper<SiteEntity> queryWrapper = new LambdaQueryWrapper<>();
        return siteMapper.selectList(queryWrapper);
    }

    @Override
    public SiteEntity getBySiteCode(String siteCode) {
        LambdaQueryWrapper<SiteEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SiteEntity::getSiteCode, siteCode);
        queryWrapper.last("LIMIT 1");
        return siteMapper.selectOne(queryWrapper);
    }

    @Override
    public SiteEntity get(int siteId) {
        return siteMapper.selectById(siteId);
    }

    @Override
    public int insertOrUpdate(SiteEntity siteEntity) {
        SiteEntity siteDb = null;
        if (null != siteEntity.getSiteId()) {
            siteDb = get(siteEntity.getSiteId());
        } else if (StringUtils.hasText(siteEntity.getSiteCode())) {
            siteDb = getBySiteCode(siteEntity.getSiteCode());
        } else {
            return 0;
        }
        if (null == siteDb) {
            insert(siteEntity);
        }
        return update(siteEntity);
    }

    @Override
    public int insert(SiteEntity siteEntity) {
        return siteMapper.insert(siteEntity);
    }

    @Override
    public int update(SiteEntity siteEntity) {
        return siteMapper.updateById(siteEntity);
    }

}
